package com.freework.report.xmlreport.groupBean.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.freework.report.base.service.filterCondition.BuilderFilterConditionSQL;
import com.freework.util.unmodifiableMap.UnmodifiableKeyMap;

public class ReportDao {

	
	public void setMustParamValues(PreparedStatement prpe,Map<String,String> mustParamValues,String []mustParamNames) throws SQLException{
		for (int i = 0; i < mustParamNames.length; i++) {
			prpe.setString(i+1, mustParamValues.get(mustParamNames[i]));
		}
		
	}
	public List<Map> query(SQLBuilderBean dbInfo,Map<String,String> mustParamValues ,Map<String,String> paramValues, Connection dbConn)
			throws SQLException {
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			BuilderFilterConditionSQL whereSQL=new BuilderFilterConditionSQL();
			String sql=dbInfo.getSql(whereSQL,paramValues);
			System.out.println(sql);
			preparedStatement = dbConn.prepareStatement(sql);
			String []mustParamNames=dbInfo.getMustParamNames();
			int index=1;
			if(mustParamNames!=null&&mustParamNames.length>0){
				index=mustParamNames.length;
				this.setMustParamValues(preparedStatement, mustParamValues,mustParamNames);
				
			}
			whereSQL.setPrepareStatement(index, preparedStatement);
			resultSet = preparedStatement.executeQuery();
			UnmodifiableKeyMap<Object> rdto = null;
			List<Map> list = new ArrayList<Map>(500);
			DBCol cols[] = dbInfo.getCols();
			while (resultSet.next()) {
				rdto = new UnmodifiableKeyMap<Object>(dbInfo.getKeysIndex());
				for (int i = 0; i < cols.length; i++) {
					rdto.putIndex(i, cols[i].getType().get(resultSet, i + 1));
				}
				list.add(rdto);
			}
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
